package com.my.socket.bio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Scarlett on 2018/6/28 0028.
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private String host;
    private int port;
    private ServerSocket serverSocket;
    private int accepterSize = 1;
    private int processorSize = 7;

    public Server(String host, int port) {
        this.host = host;
        this.port = port;

        try {
            this.serverSocket = new ServerSocket();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(this.host, this.port);
            this.serverSocket.bind(inetSocketAddress, Integer.MAX_VALUE);
        } catch (Exception e) {

        }
    }

    public void startup() {
        AtomicInteger initialStartId = new AtomicInteger(0);
        BlockingQueue<Connection> queue = new ArrayBlockingQueue<>(10000);

        for (int i = 1; i <= this.accepterSize; i++) {
            new Thread(new SocketAccepter(initialStartId, this.serverSocket, queue), "accepter-thread-" + i).start();
        }

        for (int i = 1; i <= this.processorSize; i++) {
            new Thread(new SocketProcessor(queue), "processor-thread-" + i).start();
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.startup();
    }
}
